<?php

namespace app\index\controller;

use app\model\Settlement as SettlementModel;
use app\index\middleware\Auth;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Dompdf\Dompdf;
use Dompdf\Options;
use think\facade\View;

class Settlement extends SettlementBase
{
    protected $middleware = [Auth::class];

    public function statistics()
    {
        $amount_total = SettlementModel::where('sales_id', request()->user->id)->whereLike('trade_month', '%' . input('tradeMonth') . '%')->sum('amount');

        $electricity_total = SettlementModel::where('sales_id', request()->user->id)->whereLike('trade_month', '%' . input('tradeMonth') . '%')->sum('electricity_total');

        return json(['code' => 20000, 'data' => ['amountTotal' => $amount_total, 'electricityTotal' => $electricity_total]]);
    }

    protected function getLastSixMonths()
    {
        $months = [];
        $current = new \DateTime();

        for ($i = 0; $i < 6; $i++) {
            $month = $current->format('Y-m');
            array_unshift($months, $month);
            $current->modify('-1 month');
        }

        return $months;
    }

    public function getRecentMonthReport()
    {
        $months = $this->getLastSixMonths();

        foreach ($months as $month) {
            $data[] = SettlementModel::scope('salesman')->where('trade_month', $month . '-01')->sum('amount');
        }

        return json(['code' => 20000, 'data' => $data]);
    }

    public function getExportExcel()
    {
        $models = SettlementModel::where('sales_id', request()->user->id)->select();
        $filename = 'settlements-' . date('YmdHis') . str_pad(request()->user->id, 4, '0', STR_PAD_LEFT) . '.xlsx';

        $spreadsheet = new Spreadsheet();
        $activeWorksheet = $spreadsheet->getActiveSheet();
        $activeWorksheet->setCellValue('A1', '月份');
        $activeWorksheet->setCellValue('B1', '本月收益');
        $activeWorksheet->setCellValue('C1', '本月电量');
        foreach ($models as $key => $model) {
            $activeWorksheet->setCellValue('A' . ($key + 2), date('Y-m', strtotime($model->tradeMonth)));
            $activeWorksheet->setCellValue('B' . ($key + 2), $model->amount);
            $activeWorksheet->setCellValue('C' . ($key + 2), $model->electricityTotal);
        }
        $writer = new Xlsx($spreadsheet);
        $writer->save('./storage/excel/' . $filename);

        return json(['code' => 20000, 'data' => [
            'url' => env('app_url') . '/storage/excel/' . $filename,
        ]]);
    }

    protected function imageToBase64($filePath)
    {
        // 检查文件是否存在
        if (!file_exists($filePath)) {
            throw new \Exception("文件不存在: " . $filePath);
        }

        // 获取文件MIME类型
        $mime = mime_content_type($filePath);
        if (strpos($mime, 'image/') !== 0) {
            throw new \Exception("不是有效的图片文件: " . $mime);
        }

        // 读取文件内容并编码
        $imageData = file_get_contents($filePath);
        $base64 = base64_encode($imageData);

        // 返回data URI格式
        return 'data:' . $mime . ';base64,' . $base64;
    }

    public function getExportPdf()
    {
        //http://127.0.0.1:8000/index.php/index/settlement/getExportPdf?id=1
        $settlement_id = input('id');

        $model = SettlementModel::with(['customers'])->findOrEmpty($settlement_id);

        if ($model->isEmpty()) {
            return json(['code' => 50000, 'message' => '结算单不存在']);
        }

        $customer = $model->toArray();
        $customer['electricityTotal'] = number_format($customer['electricityTotal'], 4);
        $customer['amount'] = number_format($customer['amount'], 2);
        foreach ($customer['customers'] as &$item) {
            $item['electricity'] = number_format($item['electricity'], 4);
            $item['amount'] = number_format($item['amount'], 2);
        }

        $options = new Options();
        $options->set('charset', 'utf-8');

        // instantiate and use the dompdf class
        $dompdf = new Dompdf($options);

        View::assign('img', $this->imageToBase64(root_path() . '/public/static/images/logo.png'));
        View::assign('tradeMonth', date('Y-m', strtotime($model->tradeMonth)));
        View::assign('customerCount', count($model->customers));
        View::assign('customer', $customer);
        View::assign('customers', $customer['customers']);
        View::assign('invoiceAmount', number_format($customer['amount'] / 1.13 * (1 + request()->user->invoiceTax / 100), 2));
        $dompdf->loadHtml(View::fetch(root_path() . '/public/pdf.html'));

        // (Optional) Setup the paper size and orientation
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Output the generated PDF to Browser
        $dompdf->stream();
    }
}
